#define _CRT_SECURE_NO_WARNINGS 1
#include "Heap.h"

void HPInit(Heap* php)
{
	assert(php);
	php->a =(HPTypeData*)malloc(sizeof(HPTypeData)*4);
	if (php->a == NULL)
	{
		perror("malloc fail");
		return;
	}
	php->capacity = 4;
	php->size = 0;
}
void HPDestory(Heap* php)
{
	assert(php);
	free(php->a);
	php->a = NULL;
	php->size = 0;
	php->capacity = 0;
}

void Swap(HPTypeData* p1,HPTypeData* p2)
{
	HPTypeData temp = *p1;
	*p1 = *p2;
	*p2 = temp;
}
void Adjustup(HPTypeData* a, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] > a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent= (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}
void HPPush(Heap* php, HPTypeData x)
{
	assert(php);
	if (php->a == php->capacity)
	{
		HPTypeData* temp = (HPTypeData*)realloc(php->a, sizeof(HPTypeData) * php->capacity * 2);
		if (temp == NULL)
		{
			perror("realloc fail");
			return;
		}
		php->a = temp;
		php->capacity *= 2;

	}
	php->a[php->size] = x;
	php->size++;
	//Adjustup(php->a,php->a[php->size-1]);
	Adjustup(php->a,php->size-1);

}

Adjustdown(HPTypeData* a, int n, int parent)
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child + 1] > a[child])
		{
			child++;
		}
		if (a[child] > a[parent])
		{
			Swap(&a[parent],&a[child]);
			parent = child;
			child= parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}
void HPPop(Heap* php)
{
	assert(php);
	assert(!HPEmpty(php));
	Swap(&php->a[0], &php->a[php->size - 1]);
	php->size--;

	Adjustdown(php->a, php->size, 0);
}
HPTypeData HPtop(Heap* php)
{
	assert(php);
	return php->a[0];
}
bool HPEmpty(Heap* php)
{
	assert(php);
	return php->size == 0;
}
int HPSize(Heap* php)
{
	assert(php);
	return php->size;
}